package valuecomusa.fijibus.eticket.dialog;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.HandlerThread;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.valuecomusa.Enums;
import com.valuecomusa.bmf.NfcCardInfo;
import valuecomusa.fijibus.eticket.Declarations;
import valuecomusa.fijibus.eticket.shorthaul.R;
import valuecomusa.fijibus.eticket.Utilities;
import valuecomusa.fijibus.eticket.WorkingSession;
import android.os.Handler;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: fireman
 * Date: 6/7/13
 * Time: 4:56 PM
 * To change this template use File | Settings | File Templates.
 */
public class HomeWaitCard extends Activity
{
    private final String TAG = "HomeWaitCard";
    private String SmartCardType = "BMF";
    private TextView lblTitle;
    //--
    private Handler theHandler;

//    private NfcAdapter nfcAdapter;
//    private PendingIntent mPendingIntent;

    //private BMFCard cardReader;

    public HomeWaitCard()
    {
        theHandler = new Handler();
    }

    public void onCreate(Bundle savedInstanceState)
    {
        Log.d(TAG, "onCreate...");
        super.onCreate(savedInstanceState);
        Log.d(TAG, "[onCreate] get input extra WAIT_OPTION");
        Intent input = getIntent();
        int option = input.getIntExtra("WAIT_OPTION", 0);
        if(option == 1)
        {
            Log.d(TAG, "[onCreate] setContentView(R.layout.home_wait_card_with_id);");
            setContentView(R.layout.home_wait_card_with_id);
        }
        else
        {
            Log.d(TAG, "[onCreate] setContentView(R.layout.home_wait_card);");
            setContentView(R.layout.home_wait_card);
        }

        Log.d(TAG, "[onCreate] WorkingSession.getInstance().setSAMReaderEventListener(samReaderEvent, true);");
        WorkingSession.getInstance().setSAMReaderEventListener(samReaderEvent, true);

        //--
        setResult(RESULT_CANCELED, null);

        lblTitle = (TextView)findViewById(R.id.wait_card_title);

        Log.d(TAG, "[onCreate] register button event handler");

        Button enterId = (Button) findViewById(R.id.home_wait_card_id);
        if(enterId != null)
            enterId.setOnClickListener(onEnterIdClick);
        //--
//        Log.d(TAG, "[onCreate] doGetSmartCardInfo();");
//        cardSlot = Integer.parseInt(WorkingSession.getInstance().SAM_BmfSlot);
//        doGetSmartCardInfo();

    }

    @Override
    protected void onStart()
    {
        super.onStart();
        Log.d(TAG, "onStart...");
    }

    @Override
    protected void onResume()
    {
        Log.d(TAG, "[onResume] ....");
        super.onResume();
        //doGetSmartCardInfo();

//        if (nfcAdapter != null)
//        {
//            nfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
//        }
    }

    @Override
    protected void onPause()
    {
        Log.d(TAG, "[onPause] ....");
        super.onPause();
        Log.d(TAG, "[onPause] WorkingSession.getInstance().RestoreBackupSAMReaderEventListener();");
        WorkingSession.getInstance().RestoreBackupSAMReaderEventListener();

    }

    @Override
    protected void onDestroy()
    {

        Log.d(TAG, "[onDestroy] ....");
        try {
            super.onDestroy();
//            if(cardReader != null)
//                cardReader.Dispose();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

    private View.OnClickListener onEnterIdClick = new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            Intent x = new Intent();
            x.putExtra("RESULT_OPTION_ENTER_ID", 1);

            setResult(RESULT_OK, x);
            finish();
        }
    };

//    private Runnable GetCardBalance = new Runnable()
//    {
//        @Override
//        public void run()
//        {
//            try {
//                int x = WorkingSession.getInstance().IsSmartCardTapped()
//                while ( x != 1) {
//                    Thread.sleep(100);
//                    x = WorkingSession.getInstance().getSAM_NfcCardTapped();
//                }
//            }
//            catch (Exception ex)
//            {
//                return;
//            }
//            Log.d(TAG, "[GetCardBalance] Get card balance...");
//            NfcCardInfo info = WorkingSession.getInstance().SAMGetCardBalance();
//            //cardReader.Dispose();
//            if(info != null)
//            {
//                Log.d(TAG, "[GetCardBalance] balance: " + info.Balance);
//                Log.d(TAG, "[GetCardBalance] card Issuer: " + info.CardIssuer.toString());
//                //--
//                Intent x = new Intent();
//                x.putExtra("RESULT_TAG_SERIAL", info.CardIssuer.Serial);
//                x.putExtra("RESULT_TAG_CARD_NUMBER", info.CardIssuer.LogicalNumber);
//                x.putExtra("RESULT_TAG_BALANCE", info.Balance);
//                x.putExtra("RESULT_TAG_SAM_CARD_SLOT", cardSlot);
//
//                setResult(RESULT_OK, x);
//                finish();
//            }
//        }
//    };
//
//    private boolean WaitCardReaderOpenAndTapped()
//    {
//        if(WorkingSession.getInstance().getSAM_NfcCardTapped() == -1)
//            WorkingSession.getInstance().OpenSAMCardReader(-1); //open with last information
//        Date lastTest = new Date();
//        long diffInSec = 0;
//        try {
//            do {
//                Thread.sleep(200);
//                long diffInMs = (new Date()).getTime() - lastTest.getTime();
//                diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
//                lastTest = new Date();
//            }
//            while(WorkingSession.getInstance().getSAM_NfcCardTapped() != 1 && diffInSec < 10); //waiting for 10s
//        }
//        catch (Exception ex)
//        {
//            Log.e(TAG, "[WaitCardReaderOpenAndTapped] Exception: " + ex);
//            ex.printStackTrace();
//            return false;
//        }
//        if(diffInSec >= 10)
//            return false;
//        return true;
//    }
//
//    private void doGetSmartCardInfo()
//    {
//        Log.d(TAG, "[doGetSmartCardInfo] ....");
//        new Thread(GetCardBalance).start();
//    }

//    private Boolean IsCardTapped = false;
//    private BMFCard.StateChangeListener CardReaderStateChange = new BMFCard.StateChangeListener() {
//        @Override
//        public void onStateChange(int slotNum, BMFCard.CardState prevState, BMFCard.CardState currState) {
//            Log.d(TAG, String.format("[CardReaderStateChange.onStateChange] Slot: %d,  state: %d",slotNum, currState.getValue()));
//            if(slotNum == 0)
//            {
//                if(currState.getValue() == 2) {
//                    IsCardTapped = true;
//                    theHandler.post(GetCardBalance);
//                }
//                else
//                    IsCardTapped = false;
//            }
//        }
//
//        @Override
//        public void onCardReaderState(BMFCard.CardReaderState state, String text) {
//            Log.d(TAG, String.format("[CardReaderStateChange.onCardReaderState] State: %s, text: %s",state.toString(), text));
//        }
//    };

    private WorkingSession.SAMReaderEvent samReaderEvent = new WorkingSession.SAMReaderEvent()
    {
        @Override
        public void OnReaderStateChange(String state)
        {
            Log.d(TAG, "[SAMReaderEvent.OnReaderStateChange] " + state);
            WorkingSession.getInstance().ShowToast(
                    HomeWaitCard.this,
                    "Card Reader " + state,
                    Toast.LENGTH_SHORT
                                                  );
        }

        @Override
        public void OnSAMSlotStateChange(int slot, String state)
        {
            Log.d(TAG, String.format("[SAMReaderEvent.OnSAMSlotStateChange] Slot  %d state %s", slot, state));
        }

        @Override
        public void OnSmartCardInteraction(Enums.CardProvider cardProvider, int status, String description)
        {
            Log.d(TAG, String.format("[SAMReaderEvent.OnSmartCardInteraction] %s tapped. Card status  %d, %s",
                    cardProvider.toString(), status, description));
            if (status == Declarations.SMART_CARD_STATE_PRESENT) //tap in
            {
                if (isPostResult)
                    return;
                isPostResult = true;
                tappedCardType = cardProvider;
                theHandler.post(doGetSmartCardInfoAndReturn);
//            }
//            else //may be tap out
//            {
//                //do process tap out
//            }
            }
        }
    };

    private boolean isPostResult = false;
    private Enums.CardProvider tappedCardType;
    private Runnable doGetSmartCardInfoAndReturn = new Runnable()
    {
        @Override
        public void run()
        {
            Log.d(TAG, "[doGetSmartCardInfoAndReturn] Get card balance...");
            NfcCardInfo info = WorkingSession.getInstance().SAMGetCardBalance(tappedCardType);
            //cardReader.Dispose();
            if(info != null)
            {
                Log.d(TAG, "[doGetSmartCardInfoAndReturn] balance: " + info.Balance);
                Log.d(TAG, "[doGetSmartCardInfoAndReturn] card Issuer: " + info.CardIssuer.toString());
                //--
                Log.d(TAG, "[doGetSmartCardInfoAndReturn] set result intend...");
                Intent x = new Intent();
                x.putExtra("RESULT_TAG_SERIAL", info.CardIssuer.Serial);
                x.putExtra("RESULT_TAG_CARD_NUMBER", info.CardIssuer.LogicalNumber);
                x.putExtra("RESULT_TAG_BALANCE", info.Balance);
                x.putExtra("RESULT_TAG_SAM_CARD_SLOT", tappedCardType.getValue());

                setResult(RESULT_OK, x);
                finish();
            }
        }
    };

}